package com.baiye.www.proxyHandler;

import com.baiye.www.message.RpcRequestMessage;
import com.baiye.www.message.RpcResponseMessage;
import com.baiye.www.service.ServicesFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

/**
 * @author baiye
 * @version 1.0
 * @date 2021/12/2 20:25
 */
@Slf4j
@ChannelHandler.Sharable
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcRequestMessage rpcRequestMessage) throws Exception {
        RpcResponseMessage rpcResponseMessage = new RpcResponseMessage();
        try {
            rpcResponseMessage.setSequenceId(rpcRequestMessage.getSequenceId());
            Object service = ServicesFactory.getService(Class.forName(rpcRequestMessage.getInterfaceName()));
            Method method = service.getClass().getMethod(rpcRequestMessage.getMethodName(), rpcRequestMessage.getArgTypes());
            Object invoke = method.invoke(service, rpcRequestMessage.getArgs());
            rpcResponseMessage.setResult(invoke);
        } catch (Exception e) {
            e.printStackTrace();
            rpcResponseMessage.setException(new Exception("Remote call error "+e.getCause().getMessage()));
        }
        channelHandlerContext.writeAndFlush(rpcResponseMessage);

    }
}
